package com.jiukuaidao.library.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.jiukuaidao.library.R;
import com.jiukuaidao.library.common.AppManager;
import com.jiukuaidao.library.common.dialog.CommDialog;
import com.jiukuaidao.library.common.dialog.ICallBack;
import com.jiukuaidao.library.common.dialog.LoadingDialog;
import com.jiukuaidao.library.common.page.VaryViewHelperController;
import com.jiukuaidao.library.util.ActivityUtils;
import com.jiukuaidao.library.util.NetUtils;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;


/**
 * Created by BinarySatan on 2016/5/10.
 */
public abstract class BaseActivity<T> extends AppCompatActivity implements IBaseView<T> {
    /**
     * 防止在某些地方 使用 xxxxActivity.this,  方便使用.
     */
    protected Context mContext;

    /**
     * 启动模式类.
     * LEFT : 左进左出, 以此类推.
     * 如想要左近右出. 那么需要在startActivity后加overridePendingTransition.
     * 而不能在onCreate方法内调用.
     */
    protected final int LEFT = 1, RIGHT = 2, TOP = 3, BOTTOM = 4;

    /**
     * 系统状态栏颜色更改 manager
     * {@link # https://github.com/jgilfelt/SystemBarTint}
     */
    private SystemBarTintManager mTintManager;

    /**
     * 状态栏默认颜色, 可自定义颜色
     *
     * @see #setSystemBarColor(int)
     */
    private int mDefaultSystemBarColor = Color.parseColor("#AAFF0000");
    /**
     * loading 对话框
     */
    private VaryViewHelperController mVaryViewHelperController;


    protected T mPresenter;


    protected LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;
        addToAppManager();
        setContentView(getContentLayoutId());
        ButterKnife.bind(this);
        initSystemBar();
        bindMVP();
        handleBundle(); //参数处理
        init();
    }

    protected void bindMVP() {

    }

    private void addToAppManager() {
        AppManager.getAppManager().addActivity(this);
    }

    @Override
    public void setPresenter(T persenter) {
        mPresenter = persenter;
    }


    /**
     * 初始化系统状态栏
     */
    private void initSystemBar() {
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            mTintManager = new SystemBarTintManager(this);
            mTintManager.setStatusBarTintEnabled(true);
            mTintManager.setNavigationBarTintEnabled(true);
            mTintManager.setTintColor(mDefaultSystemBarColor);
        }
    }

    /**
     * 设置系统状态栏颜色
     *
     * @param color
     */
    protected void setSystemBarColor(int color) {
        if (Build.VERSION.SDK_INT >= 19)
            mTintManager.setTintColor(color);
    }


    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);

        if (null != getTargetView())
            mVaryViewHelperController = new VaryViewHelperController(getTargetView());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        AppManager.getAppManager().removeActivity(this);
    }

    @Override
    public void finish() {
        super.finish();
        judgeOverridePendingTransition(false);
    }

    @Override
    public void showDialogOneBtn(String msg, ICallBack.OneCallBack callBack) {
        showDialogOneBtn(msg, null, callBack);
    }

    @Override
    public void showDialogOneBtn(String msg, String confirmStr, ICallBack.OneCallBack callBack) {
        CommDialog dialog = new CommDialog(this);
        dialog.setCallback(callBack);
        dialog.show(msg, confirmStr);
    }

    @Override
    public void showDialogTwoBtn(String msg, ICallBack.TwoCallBack callBack) {
        showDialogTwoBtn(msg, null, null, callBack);
    }

    @Override
    public void showDialogTwoBtn(String msg, String leftStr, String rightStr, ICallBack.TwoCallBack callBack) {
        CommDialog dialog = new CommDialog(this);
        dialog.setCallback(callBack);
        dialog.show(msg, leftStr, rightStr);
    }


    @Override
    public void showLoading(String msg) {
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.show(null);
    }

    @Override
    public void hideLoading() {
        if (mLoadingDialog != null)
            mLoadingDialog.dismiss();
    }

    @Override
    public void showEmpty(String emptyMsg) {
        mVaryViewHelperController.showEmpty(emptyMsg, null);
    }

    @Override
    public void showError(String errMsg) {
        Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showNetworkException(final IBasePresenter persenter) {
        mVaryViewHelperController.showNetworkError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkConnected()) {

                    if (persenter == null)
                        return;

                    persenter.start();

                    mVaryViewHelperController.restore();
                }
            }
        });
    }

    /**
     * 实现先登录再跳转
     *
     * @param isLogin
     * @param toClazz
     * @param fromClass
     * @param loginActivity
     */
    public void startLoginJump(boolean isLogin, Class toClazz, Class fromClass, Class loginActivity, Bundle toActivityBundle) {
        if (!isLogin) {
            if (toClazz == fromClass) {// 登录后返回需要刷新
                intentJumpForResult(loginActivity, 0);
            } else if (toClazz == null) {// 登录后返回无需刷新
                intentJump(loginActivity);
            } else {// 登录后跳转至目标activity
                Bundle b = new Bundle();
                b.putString("toActivity", toClazz.getName());
                b.putBundle("toActivityBundle", toActivityBundle);
                intentJump(loginActivity, b);
            }
        } else {
            intentJump(toClazz, toActivityBundle);
        }
    }

    private void handleBundle() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null)
            handleBundle(bundle);
    }

    protected void intentJump(Class<?> clazz) {
        intentJump(clazz, null);
    }

    protected void intentJump(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (bundle != null)
            intent.putExtras(bundle);

        startActivity(intent);
        judgeOverridePendingTransition(true);

    }

    private void judgeOverridePendingTransition(boolean isIn) {

        if (isIn) {
            if (getEnterDirection() == 0)
                overridePendingTransition(R.anim.right_in, R.anim.left_out);
            else
                switch (getEnterDirection()) {
                    case 1:
                        overridePendingTransition(R.anim.right_in, R.anim.left_out);
                        break;
                    case 2:
                        overridePendingTransition(R.anim.right_out, R.anim.left_in);
                        break;
                    case 3:
                        overridePendingTransition(R.anim.top_out, R.anim.bottom_in);
                        break;
                    case 4:
                        overridePendingTransition(R.anim.bottom_out, R.anim.top_in);
                        break;
                }
        } else {
            if (getEnterDirection() == 0)
                overridePendingTransition(R.anim.left_in, R.anim.right_out);
            else
                switch (getEnterDirection()) {
                    case 1:
                        overridePendingTransition(R.anim.left_out, R.anim.right_in);
                        break;
                    case 2:
                        overridePendingTransition(R.anim.right_out, R.anim.left_in);
                        break;
                    case 3:
                        overridePendingTransition(R.anim.top_out, R.anim.bottom_in);
                        break;
                    case 4:
                        overridePendingTransition(R.anim.bottom_out, R.anim.top_in);
                        break;
                }
        }
    }

    protected void intentJumpForResult(Class<?> clazz, int requestCode) {
        intentJumpForResult(clazz, requestCode, null);
    }

    protected void intentJumpForResult(Class<?> clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (bundle != null)
            intent.putExtras(bundle);

        startActivityForResult(intent, requestCode);
        judgeOverridePendingTransition(true);
    }

    @Override
    public void onBackPressed() {
        if (judgeIsMainActivity()) // 判断是否是MainActivity
            return;
        super.onBackPressed();
    }

    private boolean judgeIsMainActivity() {
        if (this.getClass().getSimpleName().equals("MainActivity")) {
            ActivityUtils.exitApp();
            return true;
        }
        return false;
    }

    /**
     * 对话框加载在 什么控件上.
     *
     * @return
     */
    protected abstract View getTargetView();

    /**
     * 将要打开activity的进入方向
     *
     * @return
     */
    protected int getEnterDirection() {
        return 0;
    }

    protected abstract int getContentLayoutId();

    /**
     * activity之间 传递参数处理.
     *
     * @param bundle
     */
    protected abstract void handleBundle(Bundle bundle);

    /**
     * 初始化相关操作
     */
    protected abstract void init();


}
